package com.viewsky.base.back.service.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.viewsky.base.back.bean.LoginUser;
import com.viewsky.base.back.mapper.user.UserMapper;
import com.viewsky.base.back.service.BaseService;
import com.viewsky.base.back.util.Constant;
import com.viewsky.base.back.util.JwtUtil;

import io.jsonwebtoken.Claims;

@Service("userService")
public class UserService extends BaseService
{
	@Resource(name="userMapper")
	private UserMapper userMapper;
	
	public LoginUser authenticateUser(LoginUser loginUser) throws Exception
	{
		loginUser = userMapper.getUserByLogin(loginUser);
		return loginUser;
	}
	
	public LoginUser authenticateUser(String strToken) throws Exception
	{
		Claims claims = JwtUtil.decodeToken(strToken);
		
		String strUserId = (String)claims.get("userId");
		
		LoginUser loginUser = userMapper.getUserById(strUserId);
		
		return loginUser;
	}
	
	public String generateToken(LoginUser user) throws Exception
	{
		Map<String, Object> mapClaim = new HashMap<String, Object>();
		
		mapClaim.put("userId", user.getUserId());
		mapClaim.put("userName", user.getUserName());
		mapClaim.put("orgId", user.getOrgId());
		mapClaim.put("roleId", user.getRoleId());
		
		mapClaim.put("timestamp", new Date());
		
		Date expiration = new Date(System.currentTimeMillis() +
				Constant.DEF_TOKEN_EXPIRATION);
		
		String strToken = JwtUtil.generateToken(mapClaim, expiration);
		
		return strToken;
	}
}
